import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
} from 'react';
import './index.less';
import { Modal } from 'antd';

interface Props {
  children: any;
  ref?: any;
  [key: string]: any;
  onOk?: Function;
  transCancel?: Function;
  transConfirm?: Function;
  className?: string;
  maskClosable?: boolean;
}
let customCallBack: any = null;
const IrrModal = (props: Props, ref: any) => {
  const [isShow, setIsShow] = useState<boolean>(false);
  const {
    className = '',
    title = '',
    children,
    transCancel,
    transConfirm,
    maskClosable = false,
  } = props;

  useImperativeHandle(ref, () => {
    return {
      customOpen,
    };
  });
  const onHandleCancel = () => {
    handleCancel();
    transCancel && transCancel();
  };
  const handleCancel = () => {
    setIsShow(false);
  };

  const onHandleConfirm = () => {
    transConfirm && transConfirm();
    if (transConfirm) {
      // transConfirm();
    } else {
      handleCancel();
    }
  };

  const customOpen = (callBack?: Function) => {
    if (callBack && typeof callBack === 'function') {
      customCallBack = callBack;
    }
    setIsShow(true);
  };
  useEffect(() => {
    if (!isShow && !customCallBack && typeof customCallBack !== 'function') {
      return;
    }
    const timeout = setTimeout(() => {
      isShow && customCallBack && customCallBack(true);
    }, 0);
    return () => {
      clearTimeout(timeout);
    };
  }, [isShow]);

  return (
    <>
      <Modal
        {...props}
        destroyOnClose={true}
        visible={isShow}
        onOk={onHandleConfirm}
        onCancel={onHandleCancel}
        maskClosable={maskClosable}
        title={title}
        className={`irr-modal ${className}`}
      >
        {children}
      </Modal>
    </>
  );
};

export default forwardRef(IrrModal);
